package misc

import (
	//"errors"
	"fmt"
	//"reflect"
	"strconv"
	"time"
	"dhfshop/models"
	"github.com/astaxie/beego/orm"
)

/* 生成自增数 */
type AutoInc struct {
    AutoId   int64  `orm:"column(auto_id);pk;auto"`
	ExtendId int64  `orm:"column(extend_id)"`
}

func init() {
    orm.RegisterModel(new(AutoInc))   
}

func AddAuto(m *AutoInc) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetBillNo(prefix string) (string, error) {
	rd, err := AddAuto(&AutoInc{ExtendId:1})
	if err != nil {
	    return "", err
	}
	billNo := fmt.Sprintf("%s%s%d", prefix, time.Now().Format("060102150405"),rd)
	return billNo, nil
}

func GetOrderNo()(int64, error) {
	date := time.Now().Format("060102")
	second := time.Now().Hour()*3600 + time.Now().Minute()*60 + time.Now().Second()
	rd, err := AddAuto(&AutoInc{ExtendId:1})
	if err != nil {
	    return 0, err
	}
	tradeNoStr := fmt.Sprintf("%s%05d%d", date, second, rd)
	tradeNo, err := strconv.ParseInt(tradeNoStr, 10, 64)
	if err != nil {
	   return 0, err
	}
	return tradeNo, nil
}

func GetOrderItemNo()(int64, error) {
	date := time.Now().Format("060102")
	second := time.Now().Hour()*3600 + time.Now().Minute()*60 + time.Now().Second()
	rd, err := AddAuto(&AutoInc{ExtendId:1})
	if err != nil {
	    return 0, err
	}
	orderNoStr := fmt.Sprintf("%s%05d%d", date, second, rd)
	orderNo, err := strconv.ParseInt(orderNoStr, 10, 64)
	if err != nil {
	   return 0, err
	}
	return orderNo, nil
}

func GetItemSkuNo()(int64, error) {
	date := time.Now().Format("0601021504")
	rd, err := AddAuto(&AutoInc{ExtendId:1})
	if err != nil {
	    return 0, err
	}
	ItemSkuNoStr := fmt.Sprintf("%s%d", date, rd)
	ItemSkuNo, err := strconv.ParseInt(ItemSkuNoStr, 10, 64)
	if err != nil {
	   return 0, err
	}
	return ItemSkuNo, nil
}

func GetCompanyNo() (int64, error) {
    date := time.Now().Format("060102")
	rd, err := AddAuto(&AutoInc{ExtendId:1})
	if err != nil {
	    return 0, err
	}
	idStr := fmt.Sprintf("%s%d", date, rd)
	shopId, err := strconv.ParseInt(idStr, 10, 64)
	return shopId, err
}

func GetUserNo() (int64, error) {
    date := time.Now().Format("060102")
	rd, err := AddAuto(&AutoInc{ExtendId:1})
	if err != nil {
	    return 0, err
	}
	uidstr := fmt.Sprintf("%s%d", date,rd)
	userId, err:= strconv.ParseInt(uidstr, 10, 64)
	return userId, err
}

func GetStockNo() (int64, error) {
    date := time.Now().Format("0601021504")
	rd, err := AddAuto(&AutoInc{ExtendId:1})
	if err != nil {
	    return 0, err
	}
	stockIdstr := fmt.Sprintf("%s%d", date,rd)
	stockId, err:= strconv.ParseInt(stockIdstr, 10, 64)
	return stockId, err
}

